/*
 * Copyright (C) 2022 Huawei Technologies Co., Ltd.
 * Licensed under the Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *     http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
 * PURPOSE.
 * See the Mulan PSL v2 for more details.
 */
#include "securec.h"
#include <stddef.h>
#include "string.h"
#include "tee_defines.h"
#include "tee_service_public.h"
#include "tee_log.h"
#include "se_service.h"
#include "sesrv_api.h"
#include "tee_sharemem_ops.h"

enum srv_cmd {
    SRV_SE_IPC_CMD_0 = 0x0,
};

TEE_Result tee_srv_ipc_proc_cmd(struct se_srv_msg_t *msg_in, struct se_srv_rsp_t *rsp_in)
{
    tee_service_ipc_msg msg = {{0}};
    tee_service_ipc_msg_rsp rsp = {0};
    TEE_Result ret;
    uint8_t *buf_msg = NULL;
    uint8_t *buf_rsp = NULL;
    TEE_UUID srv_uuid = SE_UUID;

    buf_msg = tee_alloc_sharemem_aux(&srv_uuid, sizeof(struct se_srv_msg_t));
    buf_rsp = tee_alloc_sharemem_aux(&srv_uuid, sizeof(struct se_srv_rsp_t));
    if (buf_msg == NULL || buf_rsp == NULL || msg_in == NULL || rsp_in == NULL) {
        tloge("buf msg is null");
        ret = TEE_ERROR_OUT_OF_MEMORY;
        goto end;
    }

    int rc = memcpy_s(buf_msg, sizeof(struct se_srv_msg_t), msg_in, sizeof(struct se_srv_msg_t));
    if (rc != 0) {
        ret = TEE_ERROR_SECURITY;
        goto end;
    }

    rsp.ret = TEE_FAIL;
    msg.args_data.arg0 = (uint64_t)(uintptr_t)(buf_msg);
    msg.args_data.arg1 = sizeof(struct se_srv_msg_t);
    msg.args_data.arg3 = (uint64_t)(uintptr_t)buf_rsp;
    msg.args_data.arg4 = sizeof(struct se_srv_rsp_t);

    tee_common_ipc_proc_cmd(SE_PATH, SRV_SE_IPC_CMD_0, &msg, SRV_SE_IPC_CMD_0, &rsp);

    ret = rsp.ret;
    if (ret == TEE_SUCCESS) {
        rc = memcpy_s(rsp_in, sizeof(struct se_srv_rsp_t), buf_rsp, sizeof(struct se_srv_rsp_t));
        if (rc != 0)
            ret = TEE_ERROR_SECURITY;
    } else {
        tloge("tee srv ipc proc cmd fail!");
    }

end:
    tee_free_sharemem(buf_rsp, sizeof(struct se_srv_rsp_t));
    tee_free_sharemem(buf_msg, sizeof(struct se_srv_msg_t));
    return ret;
}
